<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\WebController;
use Illuminate\Http\Request;
use Aitifen\Library\Xxtea\Xxtea;
use Illuminate\Support\Facades\Config;

class StudentsController extends WebController
{

    /**
     *  设置学员登录
     */
    public function setStudentToken(Request $request)
    {
        $token    = trim($request->post('token'));
        $platform = trim($request->post('platform'));

        try {
            $server = $this->getClient(STEAM_SERVICE_NAME,'AuthService');
            $server->clearHeaders();
            $data = $server->setUserToken(['token' => $token,'platformName' => $platform]);

            setcookie('STEAM-ACCESS-TOKEN',$data['accessToken'],time()+86400,'/');
        } catch(\Exception $e) {
            return $this->returnJson(301,$e->getMessage());
        }

        return $this->returnJson(0,'登录成功',['accessToken'=>$data['accessToken']]);
    }

    /**
     *  获取前台登录状态
     */
    public function getLoginStatus(Request $request)
    {
        //登录信息先从 cookie取，没有去header中去取
        $accessToken = array_key_exists('STEAM-ACCESS-TOKEN',$_COOKIE) ? $_COOKIE['STEAM-ACCESS-TOKEN'] : '';
        if (empty($accessToken)) {
            $accessToken = $request->header('STEAM-ACCESS-TOKEN');
        }

        try {
            // 获取平台信息(appkey|appsecret)
            $postData['agencyDomain'] = $request->header('host');
            $client = $this->getClient(STEAM_SERVICE_NAME, 'CommonService');
            $client->clearHeaders();
            $result = $client->getPlatformInfo($postData);

            // 将app_key|app_secret加密存储到cookie中
            $encryptString = Xxtea::encrypt(['app_key' => $result['app_key'],'app_secret' => $result['app_secret']],Config::get('common.cookie_encrypt_key'));
            setcookie('app_data',$encryptString,time()+86400,'/');
            unset($result['app_key'],$result['app_secret'],$result['platform_key'],$result['id'],$result['create_at'],$result['update_at'],$result['create_uid'],$result['update_uid']);

            //未登录
            if (!$accessToken) {
                $result['student_login_status'] = 0;
                $result['teacher_login_status'] = 0;
            } else {
                //登录
                $server = $this->getClient(STEAM_SERVICE_NAME, 'AuthService');
                $data = $server->getUserData([]);
                if (isset($data['user_type']) && $data['user_type'] == 'student') {
                    $result['student_login_status'] = 1;
                    $result['teacher_login_status'] = 0;
                } elseif (isset($data['user_type']) &&  $data['user_type'] == 'teacher') {
                    $result['teacher_login_status'] = 1;
                    $result['student_login_status'] = 0;
                } else {
                    $result['student_login_status'] = 0;
                    $result['teacher_login_status'] = 0;
                }
            }
        } catch (\Exception $e) {
            if ($e->getMessage() == '1001') {
                $result['teacher_login_status'] = 0;
                $result['student_login_status'] = 0;
            } else {
                return $this->returnJson(301, $e->getMessage());
            }
        }
        return $this->returnJson(0, '操作成功', $result);
    }

    /**
     *  获取学员详情
     */
    public function info()
    {
        try {
            $server = $this->getClient(STEAM_SERVICE_NAME,'AuthService');
            $studentInfo = $server->getStudentInfo([]);
        } catch (\Exception $e) {
            return $this->returnJson(301, $e->getMessage());
        }
        return $this->returnJson(0, '操作成功', $studentInfo);
    }

    /**
     *  修改学员信息
     */
    public function save(Request $request)
    {
        $name      = trim($request->post('name'));
        $gender    = intval($request->post('gender'));
        $grade     = intval($request->post('grade'));
        $birthday  = strtotime($request->post('birthday')) > 0 ? $request->post('birthday') : 0;
        $age       = intval($request->post('age'));
        $schoolId  = intval($request->post('school_id'));
        $address   = trim($request->post('address'));
        $headerUrl = trim($request->post('head_url'));

        $postData = [
            'name'       => $name,
            'gender'     => $gender,
            'grade'      => $grade,
            'birthday'   => $birthday,
            'age'        => $age,
            'school_id'  => $schoolId,
            'address'    => $address,
            'head_url'   => $headerUrl,
        ];

        try {
            $server = $this->getClient(STEAM_SERVICE_NAME,'AuthService');
            $bool   = $server->editStudentInfo($postData);
        } catch (\Exception $e) {
            return $this->returnJson(301, $e->getMessage());
        }
        return $this->returnJson(0, '操作成功', $bool);
    }

    public function demo()
    {
        echo 1;
    }
}